package com.atguigu.gmall.common.util;

import com.atguigu.gmall.common.constant.RedisConst;
import lombok.Data;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Data
public class UserAuthUtil {
    public static HttpServletRequest getRequest(){
        //1获取老请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest();
    }
    //获取用户的 userId
    public static Long getUserId(){
        HttpServletRequest request = getRequest();
        String header = RedisConst.USER_ID_HEADER;
        String s = request.getHeader(header);
        if (StringUtils.isEmpty(s)){
            return null;
        }
        //String 类型的 s ==> Long类型的 userId
        return Long.parseLong(s);
    }
}
